package com.sanda.androidcourse.strategy.bind;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MediatorLiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

public class CalculateViewModel extends ViewModel {
    public final MutableLiveData<String> num1 = new MutableLiveData<>("");
    public final MutableLiveData<String> num2 = new MutableLiveData<>("");
    public final MediatorLiveData<Integer> result = new MediatorLiveData<>();

    public CalculateViewModel() {
        result.setValue(0);

        result.addSource(num1, s -> autoCalculate());
        result.addSource(num2, s -> autoCalculate());
    }

    private void autoCalculate() {
        try {
            int n1 = Integer.parseInt(num1.getValue().trim());
            int n2 = Integer.parseInt(num2.getValue().trim());
            result.setValue(n1 + n2);
        } catch (Exception e) {
            result.setValue(0);
        }
    }
}

